/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Parser;

import Graph.*;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.Attributes;
/**
 *
 * @author oliviersputael
 */
public class VariablesParser extends DefaultHandler {
	public VariablesParser () throws SAXException {
		super();
		reader = XMLReaderFactory.createXMLReader();
		reader.setContentHandler(this);
		reader.setErrorHandler(this);
		vars = new ArrayList<Variables>();
		gotLastInfo = false;
	}
	
	public List<Variables> getVariablesFromFile (String filename) throws FileNotFoundException, IOException, SAXException {
		vars.clear();
		file = new FileReader(filename);
		reader.parse(new InputSource(file));
		
		return vars;
	}
	
	/*
	 * Event handlers
	 */
	
	@Override
	public void startDocument () {
		// nothing to do
	}
	
	@Override
	public void endDocument() {
		// nothing to do
	}
	
	@Override
	public void startElement (String uri, String name, String qName, Attributes attr) {
		lastOpenedTag = qName;
		gotLastInfo = false;
	}
	
	@Override
	public void endElement (String uri, String name, String qName) {
		if (qName.equals("vars")) {
			vars.add(new Variables(varName, constraint));
		}
	}
	
	@Override
	public void characters (char[] c, int start, int length) {
		if (!gotLastInfo) {
			if (lastOpenedTag.equals("name")) {
				varName = String.copyValueOf(c, start, length);
				gotLastInfo = true;
			}
			else if (lastOpenedTag.equals("constraint")) {
				constraint = new Integer(String.copyValueOf(c, start, length));
				gotLastInfo = true;
			}
			else {
				// junk characters : \n etc
			}
		}
	}
	
	private XMLReader reader;
	private FileReader file;
	private List<Variables> vars;
	private String lastOpenedTag;
	private boolean gotLastInfo;
	private String varName;
	private int constraint;
}
